package face.pay.token;

import face.pay.AbstractRedis;
import face.pay.constant.CacheKey;
import face.pay.dao.CpnWxAppInfoDao;
import face.pay.entity.CpnWxAppInfo;
import face.pay.redis.RedisUtils;
import face.pay.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.TicketAPI;
import weixin.popular.api.TokenAPI;
import weixin.popular.bean.ticket.Ticket;
import weixin.popular.bean.token.Token;

import java.util.Date;

/**
 *
 */
@Component
@Slf4j
public class AccessTokenTask {

    @Autowired
    CpnWxAppInfoDao cpnWxAppInfoDao;

    @Autowired
    AbstractRedis redisUtils;
    /**
     * 定期检测AccessToken  ticket 及时更新
     */
    @Scheduled(cron = "0/30 * * * * ?")
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void keepAliveAccessToken(){

        try{
            log.error("刷新AccessToken");
            CpnWxAppInfo cpnWxAppInfo =  this.cpnWxAppInfoDao.getById(1);
            log.info("cpnWxAppInfo "+cpnWxAppInfo.toString());
            Token token =  TokenAPI.token(cpnWxAppInfo.getAppId(),cpnWxAppInfo.getSecret());


            String accessToken  =  token.getAccess_token();

            log.info("新accessToken:"+accessToken);
            cpnWxAppInfo.setAccess_token(accessToken);

            /**
             * 获取ticket
             */
            log.info("获取ticket");
            Ticket jsapi_ticket =  TicketAPI.ticketGetticket(accessToken,"jsapi");
            String ticket =   jsapi_ticket.getTicket();
            cpnWxAppInfo.setTicket(ticket);
            log.info("更新accessToken 获取ticket");

            Ticket card_ticket   =     TicketAPI.ticketGetticket(accessToken,"wx_card");
            String cardTicket =  card_ticket.getTicket();
            log.info("更新accessToken 获取card ticket:" + cardTicket);

            cpnWxAppInfo.setCardTicket(cardTicket);
            cpnWxAppInfo.setToken_create_time(DateUtil.getNowTime());
            cpnWxAppInfo.setUpdatedTime(DateUtil.getNowTime());

            log.info(cpnWxAppInfo.toString());

            this.cpnWxAppInfoDao.updateToken(cpnWxAppInfo);

            redisUtils.set(CacheKey.WX_APP_INFO,cpnWxAppInfo,60*60*2);

            log.info("更新accessToken结束");
        }catch (Exception e){
            log.error("刷新token失败",e);
        }

    }

}
